import 'package:connectivity/connectivity.dart';
import 'package:df/page/web/web_page.dart';
import 'dart:async';
import 'dart:collection';
import 'package:df/page/router/router.dart';
import 'package:df/page/splash/splash_page.dart';
import 'package:df/page/splash/update_app.dart';
import 'package:df/page/splash/update_utils.dart';
import 'package:df/page/web/js_callback.dart';
import 'package:df/page/web/language_locale.dart';
import 'package:df/page/web/permission_key.dart';
import 'package:df/page/web/web_constant.dart';
import 'package:df/utils/logger_utils.dart';
import 'package:df/utils/sp_key.dart';
import 'package:df/utils/sp_utils.dart';
import 'package:df/widgets/toast_utils.dart';
import 'package:flutter/foundation.dart';
import 'package:flutter/material.dart';
import 'package:flutter/services.dart';
import 'package:flutter_inappwebview/flutter_inappwebview.dart';
import 'package:go_router/go_router.dart';
import 'package:intl/intl.dart';
import 'package:permission_handler/permission_handler.dart';
import 'package:provider/provider.dart';
import 'package:url_launcher/url_launcher.dart';
import 'dart:io';
import 'package:df/generated/l10n.dart';


class MainPage extends StatefulWidget {
  final String wechatUnionId;
  final String larkUnionId;
  final String userId;
  const MainPage({Key? key, required this.wechatUnionId, required this.larkUnionId, required this.userId}) : super(key: key);

  // @override
  // _MainPageState createState() => _MainPageState();
  @override
  State<StatefulWidget> createState() {
    String url = Web.indexUrl + Web.kWechatUnionId + Web.kEqual + wechatUnionId
        + Web.kAnd+ Web.kLarkUnionId + Web.kEqual + larkUnionId
        + Web.kAnd+ Web.kUserId + Web.kEqual + userId
        + Web.kAnd+ Web.kPlatform + Web.kEqual + Splash.vPlatform
    ;
    LogUtils.v('【浏览器】最终地址= ' + url);
    return _MainPageState(url);
  }
}

class _MainPageState extends State<MainPage> {
  // 当前在第几(底部)菜单。
  int _currentIndex = 2;
  _MainPageState(this._lastLoadedUrl);
  final String updateUrl = 'https://gitee.com/hehongdan/room/raw/Dev/custom.json';
  final String bkbbUrl = 'https://sps.pheyma.com/wxhhrp/index.html#/mine/0|0';
  PullToRefreshController? pullToRefreshController;
  MaterialStatesController canGoBackController = MaterialStatesController();
  MaterialStatesController canGoForwardController = MaterialStatesController();
  final GlobalKey webViewKey = GlobalKey();
  double progress = 0;
  final urlController = TextEditingController();

  InAppWebViewController? _webViewController;
  String _lastLoadedUrl;
  bool _isConnect = true;
  Future<void> _checkConnect() async {
    var connectivityResult = await (Connectivity().checkConnectivity());
    setState(() {
      _isConnect = connectivityResult != ConnectivityResult.none;
    });
  }
  void _retryLoad() {
    if (_isConnect) {
      _webViewController?.reload();
    } else {
      _checkConnect();
    }
  }
  Widget buildConnectView5(BuildContext context) {
    return
      Center(
        child: Column(
          mainAxisAlignment: MainAxisAlignment.center,
          children: [
            Text('加载失败，请检查网络后再试'),
            ElevatedButton(
              onPressed: () {
                _retryLoad();
              },
              child: Text('重试'),
            ),
          ],
        ),
      );
  }
  Widget buildInAppWebView5(BuildContext context) {
    final Completer<InAppWebViewController> controllerCompleter = Completer<InAppWebViewController>();

    return
      InAppWebView(
        //【JsFlutter-2/2】==============================================
        // initialData: InAppWebViewInitialData(data: htmlData),
        initialUrlRequest: URLRequest(url: WebUri(_lastLoadedUrl)),
        // initialUrlRequest: URLRequest(url: WebUri('https://192.168.126.128:3000/')),
        // initialUrlRequest: URLRequest(url: WebUri('https://sps.pheyma.com/wxhhapps/index.html#/Mine/wxUnionId=ok-Ft6Fan2WipBocq_NzlK2Yy790&flyUnionId=on_4ef6c0235db38923b0d6002c5fa39f0a&userId=4660028360051142119&platform=android')),
        // initialUrlRequest: URLRequest(url: WebUri('https://www.jq22.com/yanshi18789')),
        //【JsFlutter-2/2】==============================================
        initialSettings: kInAppWebViewSettings,
        key: webViewKey,
        pullToRefreshController: pullToRefreshController,
        initialUserScripts: UnmodifiableListView<UserScript>([]),
        // 禁用 SSL 证书验证，总是信任
        onReceivedServerTrustAuthRequest: (controller, challenge) async {
          return ServerTrustAuthResponse(action: ServerTrustAuthResponseAction.PROCEED);
        },
        onConsoleMessage: (controller, consoleMessage) {
          if(false) {
            LogUtils.d(
                '=============================================================================================================='
                    '\n【Js控制台】\n${consoleMessage}\n'
                    '=============================================================================================================='
            );
          }
        },
        onWebViewCreated: (controller) async {
          _webViewController = controller;
          controllerCompleter.complete(controller);
          controllerCompleter.future.then((value) {
            LogUtils.v('【浏览器】controllerCompleter=》=》=》=》=》=》=》=》=》=》=》=》=》=》=》=》=》= ${value}');
          });
          WebPage.addJsHandler(context, controller);
        },

        onTitleChanged: (controller, title) {
          LogUtils.v('【浏览器】标题变为= ${_lastLoadedUrl.toString()}');
          setBackOrForwardView();
        },
        onLoadStart: (controller, url) async {
          LogUtils.w('【浏览器】加载开始= ${url.toString()}');

          setState(() {
            urlController.text = url.toString();
          });
        },
        onLoadError: (controller, url, code, message) async {
          LogUtils.w('【浏览器】页面出错${url.toString()}');
          pullToRefreshController?.endRefreshing();
        },
        onLoadStop: (controller, url) async {
          LogUtils.w('【浏览器】加载结束= ${url.toString()}');

          //_checkConnection();
          pullToRefreshController?.endRefreshing();
          setState(() {
            urlController.text = url.toString();
            _lastLoadedUrl = url.toString();
          });
          _webViewController?.canGoBack().then((can) {
            LogUtils.v("【点击事件】是否可以回退= ${can}");
            if(can) {
              setState(() {
                canGoBackController.update(MaterialState.disabled, false);
              });
            } else {
              setState(() {
                canGoBackController.update(MaterialState.disabled, true);
              });
            }
          });
          _webViewController?.canGoForward().then((can) {
            LogUtils.v("【点击事件】是否可以前进= ${can}");
            if(can) {
              setState(() {
                canGoForwardController.update(MaterialState.disabled, false);
              });
            } else {
              setState(() {
                canGoForwardController.update(MaterialState.disabled, true);
              });
            }
          });

        },
        onReceivedError: (controller, request, error) {
          pullToRefreshController?.endRefreshing();
        },
        onProgressChanged: (controller, progress) {
          if (progress == 100) {
            pullToRefreshController?.endRefreshing();
          }
          setState(() {
            this.progress = progress / 100;
            LogUtils.v('状态= ${_lastLoadedUrl}');
          });
        },
        onUpdateVisitedHistory: (controller, url, isReload) {
          setState(() {
            urlController.text = url.toString();
          });
        },
        onPermissionRequest: (controller, request) async {
          return PermissionResponse(
              resources: request.resources,
              action: PermissionResponseAction.GRANT);
        },

        shouldOverrideUrlLoading: (controller, navigationAction) async {
          var uri = navigationAction.request.url!;
          if (![
            "http", "https", "file", "chrome", "data", "javascript", "about"
          ].contains(uri.scheme)) {
            if (await canLaunchUrl(uri)) {
              await launchUrl(
                uri,
              );
              return NavigationActionPolicy.CANCEL;
            }
          }
          return NavigationActionPolicy.ALLOW;
        },

      );
  }
  @override
  void initState() {
    super.initState();

    pullToRefreshController = kIsWeb || ![TargetPlatform.iOS, TargetPlatform.android].contains(defaultTargetPlatform)
        ? null
        : PullToRefreshController(
      settings: PullToRefreshSettings(
        color: Colors.cyan,
      ),
      onRefresh: () async {
        if (defaultTargetPlatform == TargetPlatform.android) {
          _webViewController?.reload();
        } else if (defaultTargetPlatform == TargetPlatform.iOS) {
          _webViewController?.loadUrl(urlRequest: URLRequest(url: await _webViewController?.getUrl()));
        }
      },
    );

    // 初始化时检测网络状态
    _checkConnect();
    // 监听网络状态变化
    Connectivity().onConnectivityChanged.listen((result) {
      setState(() {
        bool connect = (result != ConnectivityResult.none);
        LogUtils.w("【网络】监听网络状态= {$connect}");
      });
    });
  }

  @override
  void dispose() {
    super.dispose();
  }

  void _onTabTapped(int index) {
    setState(() {
      _currentIndex = index;
    });
    LogUtils.w('【主页】点击下标= ${index}');

    switch (index) {
      case 0:
      //setBackOrForwardView();
        _webViewController?.canGoBack().then((can) {
          LogUtils.v("【点击事件】是否可以回退= ${can}");
          if(can) {
            _webViewController?.goBack();
          } else {
            ToastUtils.show(S.of(context).firstPage);
          }
        });
        break;
      case 1:
      //setBackOrForwardView();
        _webViewController?.canGoForward().then((can) {
          LogUtils.v("【点击事件】是否可以回退= ${can}");
          if(can) {
            _webViewController?.goForward();
          } else {
            ToastUtils.show(S.of(context).lastPage);
          }
        });
        break;
      case 2:
        LogUtils.v("【点击事件】浏览器首页= ${_lastLoadedUrl}");
        _webViewController?.loadUrl(urlRequest: URLRequest(url: WebUri(_lastLoadedUrl)));
        break;
      case 3:
        LogUtils.v("【点击事件】浏览器首页= ${Web.massageUrl}");
        _webViewController?.loadUrl(urlRequest: URLRequest(url: WebUri(Web.massageUrl)));
        break;
      case 4:
        LogUtils.v("【点击事件】浏览器首页= ${Web.userUrl}");
        _webViewController?.loadUrl(urlRequest: URLRequest(url: WebUri(Web.userUrl)));
        break;

      default:
        LogUtils.w('【主页】点击下标(没匹配到)= ${index}');
    }
  }

  @override
  Widget build(BuildContext context) {
    return Scaffold(
      body: buildSafeArea2(context),

      bottomNavigationBar: BottomNavigationBar(
        currentIndex: _currentIndex,
        onTap: _onTabTapped,
        type: BottomNavigationBarType.fixed,//每个项的宽度
        // selectedItemColor: Theme.of(context).accentColor, // 设置选中项的颜色
        // unselectedItemColor: Colors.grey, // 设置未选中项的颜色
        selectedLabelStyle: TextStyle(fontSize: 1), // 调整选中项文本的大小
        unselectedLabelStyle: TextStyle(fontSize: 1), // 调整未选中项文本的大小

        items: [
          BottomNavigationBarItem(
            icon: Icon(Icons.arrow_back),
            label: '',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.arrow_forward),
            label: '',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.home),
            label: '',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.message),
            label: '',
          ),
          BottomNavigationBarItem(
            icon: Icon(Icons.person),
            label: '',
          ),
        ],
      ),

    );
  }

  Future<void> delayedOperation() async {
    print("开始执行延迟操作...");

    // 延迟2秒后执行
    await Future.delayed(Duration(seconds: 2));
    if(_webViewController != null) {
      _webViewController?.stopLoading();

      LogUtils.w("已停止");
    } else {
      LogUtils.w("已停止...");
    }

    print("延迟操作执行完成！");
  }

  Widget buildStack4(BuildContext context) {
    return Stack(
      children: [
        // 第一层视图
        Visibility(
          visible: _isConnect,//showWebLayer
          child: buildInAppWebView5(context),
        ),
        // 第二层视图
        Visibility(
          visible: !_isConnect,
          child: buildConnectView5(context),
        ),

        (progress < 1.0) ? LinearProgressIndicator(value: progress) : Container(),
      ],
    );
  }


  //可以退出应用
  Widget buildWillPopScope3(BuildContext context) {
    bool _doubleBackToExitPressedOnce = false;

    return WillPopScope(
      onWillPop: () async {
        if (await _webViewController?.canGoBack() ?? false) {
          _webViewController?.goBack();
          return false;
        } else {
          if (_doubleBackToExitPressedOnce) {
            SystemNavigator.pop(); // 【2/2】不会Flutter的GoRouter用下骚操作
            return true;
          }
          _doubleBackToExitPressedOnce = true;
          ToastUtils.show(S.current.exitAgain);

          // 如果 2 秒内再次按下，则退出应用
          Future.delayed(Duration(seconds: 2), () {
            _doubleBackToExitPressedOnce = false;
          });

          return false;
        }
      },

      child: buildStack4(context),
    );
  }

  //控制顶部、底部的可见性
  Widget buildSafeArea2(BuildContext context) {
    return SafeArea(
      top: true,
      bottom: false,
      left: false,
      right: false,

      child: buildWillPopScope3(context),
    );
  }


  void setBackOrForwardView() {
    _webViewController?.canGoBackOrForward(steps: 1).then((can) {
      LogUtils.i("【点击事件】是否可以回退、前进一步${can}");
    });
    _webViewController?.canGoBack().then((can) {
      LogUtils.v("【点击事件】是否可以回退= ${can}");
      if(can) {
        setState(() {
          canGoBackController.update(MaterialState.disabled, false);
        });
      } else {
        setState(() {
          canGoBackController.update(MaterialState.disabled, true);
        });
      }
    });
    _webViewController?.canGoForward().then((can) {
      LogUtils.v("【点击事件】是否可以前进= ${can}");
      if(can) {
        setState(() {
          canGoForwardController.update(MaterialState.disabled, false);
        });
      } else {
        setState(() {
          canGoForwardController.update(MaterialState.disabled, true);
        });
      }
    });
  }

}
